using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using MusicLibrary.Server.Models;
using MusicLibrary.Server.Data;
using System.Linq;

[Authorize]
[ApiController]
[Route("api/playlists")]
public class PlaylistController : ControllerBase
{
    private readonly MusicLibraryContext _context;
    public PlaylistController(MusicLibraryContext context) => _context = context;

    // 获取我的歌单
    [HttpGet("my")]
    public async Task<IActionResult> GetMyPlaylists()
    {
        var userId = int.Parse(User.FindFirst("id")?.Value);
        var playlists = await _context.Playlists
            .Where(p => p.OwnerId == userId)
            .Include(p => p.Songs)
            .ToListAsync();

        return Ok(new { code = 0, data = playlists });
    }

    // 获取公共歌单
    [HttpGet("public")]
    public async Task<IActionResult> GetPublicPlaylists([FromQuery] string search = "")
    {
        var query = _context.Playlists
            .Include(p => p.Owner)
            .Include(p => p.Songs)
            .AsQueryable();

        if (!string.IsNullOrWhiteSpace(search))
        {
            search = search.ToLower();
            query = query.Where(p => 
                p.Name.ToLower().Contains(search) || 
                p.Description.ToLower().Contains(search));
        }

        var playlists = await query.ToListAsync();
        return Ok(new { code = 0, data = playlists });
    }

    // 创建歌单
    [HttpPost]
    public async Task<IActionResult> CreatePlaylist([FromBody] PlaylistCreateRequest request)
    {
        var userId = int.Parse(User.FindFirst("id")?.Value);
        var playlist = new Playlist
        {
            Name = request.Name,
            Description = request.Description,
            OwnerId = userId,
            CreatedAt = DateTime.UtcNow
        };

        _context.Playlists.Add(playlist);
        await _context.SaveChangesAsync();

        return Ok(new { code = 0, data = playlist });
    }

    // 更新歌单
    [HttpPut("{id}")]
    public async Task<IActionResult> UpdatePlaylist(int id, [FromBody] PlaylistUpdateRequest request)
    {
        var userId = int.Parse(User.FindFirst("id")?.Value);
        var playlist = await _context.Playlists.FindAsync(id);

        if (playlist == null)
        {
            return NotFound(new { code = 1, message = "歌单不存在" });
        }

        if (playlist.OwnerId != userId)
        {
            return Forbid();
        }

        playlist.Name = request.Name;
        playlist.Description = request.Description;

        await _context.SaveChangesAsync();
        return Ok(new { code = 0, data = playlist });
    }

    // 删除歌单
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeletePlaylist(int id)
    {
        var userId = int.Parse(User.FindFirst("id")?.Value);
        var playlist = await _context.Playlists.FindAsync(id);

        if (playlist == null)
        {
            return NotFound(new { code = 1, message = "歌单不存在" });
        }

        if (playlist.OwnerId != userId)
        {
            return Forbid();
        }

        _context.Playlists.Remove(playlist);
        await _context.SaveChangesAsync();

        return Ok(new { code = 0, message = "删除成功" });
    }

    // 添加歌曲到歌单
    [HttpPost("{id}/songs/{songId}")]
    public async Task<IActionResult> AddSongToPlaylist(int id, int songId)
    {
        var userId = int.Parse(User.FindFirst("id")?.Value);
        var playlist = await _context.Playlists
            .Include(p => p.Songs)
            .FirstOrDefaultAsync(p => p.Id == id);

        if (playlist == null)
        {
            return NotFound(new { code = 1, message = "歌单不存在" });
        }

        if (playlist.OwnerId != userId)
        {
            return Forbid();
        }

        var song = await _context.Songs.FindAsync(songId);
        if (song == null)
        {
            return NotFound(new { code = 1, message = "歌曲不存在" });
        }

        if (!playlist.Songs.Any(s => s.Id == songId))
        {
            playlist.Songs.Add(song);
            await _context.SaveChangesAsync();
        }

        return Ok(new { code = 0, message = "添加成功" });
    }

    // 从歌单中移除歌曲
    [HttpDelete("{id}/songs/{songId}")]
    public async Task<IActionResult> RemoveSongFromPlaylist(int id, int songId)
    {
        var userId = int.Parse(User.FindFirst("id")?.Value);
        var playlist = await _context.Playlists
            .Include(p => p.Songs)
            .FirstOrDefaultAsync(p => p.Id == id);

        if (playlist == null)
        {
            return NotFound(new { code = 1, message = "歌单不存在" });
        }

        if (playlist.OwnerId != userId)
        {
            return Forbid();
        }

        var song = playlist.Songs.FirstOrDefault(s => s.Id == songId);
        if (song != null)
        {
            playlist.Songs.Remove(song);
            await _context.SaveChangesAsync();
        }

        return Ok(new { code = 0, message = "移除成功" });
    }
}

public class PlaylistCreateRequest
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public class PlaylistUpdateRequest
{
    public string Name { get; set; }
    public string Description { get; set; }
}